"""
项目相关路由
"""
from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify
from flask_login import login_required, current_user
from datetime import datetime
from app.models import User
from app.services import ProjectService, DashboardService

# 创建蓝图
project_bp = Blueprint('project', __name__, url_prefix='/project')

@project_bp.route('/')
@login_required
def list_projects():
    """项目列表"""
    page = request.args.get('page', 1, type=int)
    per_page = 10
    projects = ProjectService.get_projects(page=page, per_page=per_page)
    
    # 获取项目统计数据
    dashboard_data = DashboardService.get_dashboard_stats()
    stats = dashboard_data['stats']
    
    # 计算总页数
    total_pages = (projects.total + per_page - 1) // per_page
    
    # 获取所有用户和客户，用于项目立项表单
    users = User.query.all()
    from app.models import Customer
    customers = Customer.query.all()
    
    # 获取管理者和销售负责人列表
    managers = User.query.filter(User.role == '管理员').all()
    sales_managers = User.query.filter(User.role == '销售').all()
    
    # 获取项目来源列表
    sources = ['内部创建', '客户委托', '招标项目', '合作伙伴推荐']
    
    return render_template('project_list.html', 
                          projects=projects, 
                          stats=stats, 
                          users=users, 
                          customers=customers,
                          managers=managers,
                          sales_managers=sales_managers,
                          sources=sources,
                          page=page,
                          per_page=per_page,
                          total_pages=total_pages)

@project_bp.route('/create', methods=['GET', 'POST'])
@login_required
def create_project():
    """创建项目"""
    if request.method == 'POST':
        name = request.form.get('name')
        description = request.form.get('description')
        start_date = datetime.strptime(request.form.get('start_date'), '%Y-%m-%d').date() if request.form.get('start_date') else None
        end_date = datetime.strptime(request.form.get('end_date'), '%Y-%m-%d').date() if request.form.get('end_date') else None
        project_type = request.form.get('project_type')
        project_source = request.form.get('project_source')
        estimated_budget = float(request.form.get('estimated_budget')) if request.form.get('estimated_budget') else 0.0
        
        project = ProjectService.create_project(
            name=name,
            description=description,
            start_date=start_date,
            end_date=end_date,
            project_type=project_type,
            project_source=project_source,
            estimated_budget=estimated_budget,
            manager_id=current_user.id
        )
        
        flash('项目创建成功')
        return redirect(url_for('project.list_projects'))
    
    # 获取所有用户和客户，用于表单选择
    users = User.query.all()
    from app.models import Customer
    customers = Customer.query.all()
    
    return render_template('project_form.html', users=users, customers=customers)

@project_bp.route('/<int:project_id>')
@login_required
def view_project(project_id):
    """查看项目详情"""
    project = ProjectService.get_project(project_id)
    
    if not project:
        flash('您没有权限查看此项目')
        return redirect(url_for('project.list_projects'))
    
    # 获取项目任务分页数据
    page = request.args.get('page', 1, type=int)
    per_page = 10  # 每页显示10条记录
    tasks_pagination = ProjectService.get_project_tasks_paginated(
        project_id, current_user.id, page=page, per_page=per_page)
    
    # 获取项目角色分页数据
    roles_page = request.args.get('roles_page', 1, type=int)
    roles_per_page = 10  # 每页显示10条记录
    project_roles_pagination = ProjectService.get_project_roles_paginated(
        project_id, page=roles_page, per_page=roles_per_page)
    
    # 获取项目里程碑
    milestones = ProjectService.get_project_milestones(project_id)
    
    return render_template('project_detail.html', 
                          project=project, 
                          tasks=tasks_pagination.items,
                          tasks_pagination=tasks_pagination,
                          project_roles_pagination=project_roles_pagination,
                          milestones=milestones)

@project_bp.route('/<int:project_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_project(project_id):
    """编辑项目"""
    project = ProjectService.get_project(project_id)
    
    if not project:
        flash('您没有权限编辑此项目')
        return redirect(url_for('project.list_projects'))
    
    if request.method == 'POST':
        name = request.form.get('name')
        description = request.form.get('description')
        start_date = datetime.strptime(request.form.get('start_date'), '%Y-%m-%d').date() if request.form.get('start_date') else None
        end_date = datetime.strptime(request.form.get('end_date'), '%Y-%m-%d').date() if request.form.get('end_date') else None
        project_type = request.form.get('project_type')
        project_source = request.form.get('project_source')
        estimated_budget = float(request.form.get('estimated_budget')) if request.form.get('estimated_budget') else 0.0
        status = request.form.get('status')
        
        success = ProjectService.update_project(
            project_id=project_id,
            name=name,
            description=description,
            start_date=start_date,
            end_date=end_date,
            project_type=project_type,
            project_source=project_source,
            estimated_budget=estimated_budget,
            status=status
        )
        
        if success:
            flash('项目更新成功')
            return redirect(url_for('project.view_project', project_id=project_id))
        else:
            flash('您没有权限编辑此项目')
            return redirect(url_for('project.list_projects'))
    
    # 获取所有用户和客户，用于表单选择
    users = User.query.all()
    from app.models import Customer
    customers = Customer.query.all()
    
    return render_template('project_form.html', project=project, users=users, customers=customers)

@project_bp.route('/<int:project_id>/delete', methods=['POST'])
@login_required
def delete_project(project_id):
    """删除项目"""
    success = ProjectService.delete_project(project_id)
    
    if success:
        flash('项目删除成功')
    else:
        flash('您没有权限删除此项目')
    
    return redirect(url_for('project.list_projects'))

@project_bp.route('/<int:project_id>/task/create', methods=['GET', 'POST'])
@login_required
def create_task(project_id):
    """创建项目任务"""
    project = ProjectService.get_project(project_id)
    
    if not project:
        flash('您没有权限为此项目创建任务')
        return redirect(url_for('project.list_projects'))
    
    if request.method == 'POST':
        name = request.form.get('name')
        description = request.form.get('description')
        start_date = datetime.strptime(request.form.get('start_date'), '%Y-%m-%d').date() if request.form.get('start_date') else None
        end_date = datetime.strptime(request.form.get('end_date'), '%Y-%m-%d').date() if request.form.get('end_date') else None
        priority = request.form.get('priority')
        assigned_to = int(request.form.get('assigned_to')) if request.form.get('assigned_to') else None
        
        task = ProjectService.create_task(
            project_id=project_id,
            name=name,
            description=description,
            start_date=start_date,
            end_date=end_date,
            priority=priority,
            assigned_to=assigned_to
        )
        
        flash('任务创建成功')
        return redirect(url_for('project.view_project', project_id=project_id))
    
    # 获取可分配的用户列表
    users = User.query.all()
    return render_template('task_form.html', project=project, users=users)

@project_bp.route('/initiation/ajax', methods=['POST'])
@login_required
def project_initiation_ajax():
    """项目立项AJAX处理"""
    try:
        name = request.form.get('name')
        description = request.form.get('description')
        start_date = datetime.strptime(request.form.get('start_date'), '%Y-%m-%d').date() if request.form.get('start_date') else None
        end_date = datetime.strptime(request.form.get('end_date'), '%Y-%m-%d').date() if request.form.get('end_date') else None
        project_type = request.form.get('project_type')
        project_source = request.form.get('project_source')
        estimated_budget = float(request.form.get('budget')) if request.form.get('budget') else 0.0
        manager_id = int(request.form.get('manager_id')) if request.form.get('manager_id') else current_user.id
        customer_id = int(request.form.get('customer_id')) if request.form.get('customer_id') else None
        
        project = ProjectService.create_project(
            name=name,
            description=description,
            start_date=start_date,
            end_date=end_date,
            project_type=project_type,
            project_source=project_source,
            estimated_budget=estimated_budget,
            manager_id=manager_id,
            customer_id=customer_id
        )
        
        return jsonify({
            'success': True,
            'message': '项目立项成功',
            'project_id': project.id
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'项目立项失败: {str(e)}'
        }), 400